<?php
/**
 * 文件上传
 * @author  hdxj <[<2300071698@qq.com>]>
 */
class Upload
{
	//储存上传文件的目录
	public $dir;

	//上传允许的大小
	public $allowSize=2000000;

	//上传允许的类型,必须小写
	public $allowType=array('jpeg','jpg','gif','png');

	/**
	 * 构造函数
	 * @param [type] $dir       [储存目录]
	 * @param string $allowSize [允许大小]
	 * @param array  $allowType [允许类型]
	 */
	public function __construct($dir=null,$allowSize='',$allowType=array())
	{
		$this->setUploadDir($dir);
		if(!empty($allowSize))$this->allowSize = $allowSize;
		if(!empty($allowType))$this->allowType = $allowType;
	}

	/**
	 * 设置上传目录
	 * @param [type] $dir [description]
	 */
	private function setUploadDir($dir)
	{
		//如果没有传递目录，我们给配置一个目录
		if(empty($dir))$this->dir ='upload/'.date("Y/m/d");
		//创建目录
		is_dir($this->dir) or mkdir($this->dir,0755,true);
	}

	/**
	 * 上传文件
	 * @return [type] [description]
	 */
	public function upload()
	{
		$files = $this->format();
		//对文件合法性检验
		$files = $this->check($files);

		$files = $this->moveFile($files);

		return $files;

	}

	/**
	 * 将上传的表单数据统一
	 * @return [type] [description]
	 */
	private function format()
	{
		$data =array();
		foreach($_FILES as $file)
		{
			if(is_array($file['name']))
			{
				foreach($file['name'] as $id=>$value)
				{
					$tmp['name']=$file['name'][$id];
					$tmp['type']=$file['type'][$id];
					$tmp['tmp_name']=$file['tmp_name'][$id];
					$tmp['error']=$file['error'][$id];
					$tmp['size']=$file['size'][$id];
					$tmp['time']=time();
					$data[]=$tmp;
				}
			}
			else
			{
				$info = pathinfo($file['name']);
				$data[]=$file;
			}
		}
		return $data;
	}

	/**
	 * 检测文件合法性
	 * @param  [type] $files [description]
	 * @return [type]        [description]
	 */
	private function check($files)
	{
		$data=array();
		foreach($files as $file)
		{
			if(!is_uploaded_file($file['tmp_name'])){
				continue;
			}
			if($file['error']!=0)
			{
				continue;
			}
			if($file['size']>$this->allowSize)
			{
				continue;
			}
			$info = pathinfo($file['name']);
			if(!in_array(strtolower($info['extension']), $this->allowType))
			{
				continue;
			}
			$data[]=$file;
		}
		return $data;
	}

	/**
	 * 移动上传的文件
	 * @param  [type] $files [description]
	 * @return [type]        [description]
	 */
	private function moveFile($files)
	{
		$data=array();
		foreach($files as $file)
		{
			$info = pathinfo($file['name']);
			//目标文件（储存在服务器上的文件）
			$destination =$this->dir.'/'.mt_rand().time().'.'.$info['extension'];
			if(move_uploaded_file($file['tmp_name'], $destination))
			{
				$data[]=$file;
			}
		}
		return $data;
	}
}













